package org.dallasrowing.logbook.ui.controller;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import org.dallasrowing.logbook.Config;
import org.dallasrowing.logbook.report.GenerateJasperReport;
import org.dallasrowing.logbook.ui.view.LogBookWindow;
import org.dallasrowing.logbook.ui.view.ReportsWindow;
import org.dallasrowing.logbook.util.DBConnector;

public class ReportsControllerImpl implements ReportsController {

	private static final String CURRENT_YEAR = "CURRENT_YEAR";
	private LogBookWindow mainWindow;
	private ReportsWindow window;
	private File[] reports;
	private Connection connection;

	public ReportsControllerImpl(LogBookWindow mainWindow) {
		this.mainWindow = mainWindow;
		this.connection = DBConnector.getConnection();
	}

	public void openReportsWindow(ReportsWindow window)
	{
		this.window = window;
		registerListeners();
		fillAvailReports();
		window.show();
	}

	private void fillAvailReports() {
		File reportDirectory = Config.getReportsDirectory();
		reports = reportDirectory.listFiles(new FileFilter() {
		
			public boolean accept(File pathname) {
				return (pathname.toString().endsWith(".jrxml"));
			}
		});
		
		for (File report : reports)
		{
			window.addReport(report.getName().replaceAll(".jrxml", ""));
		}
	}

	private void registerListeners() {
		window.setGenerateReportListener(new Runnable() {
		
			public void run() {
				generateReport();
			}
		});
	}

	protected void displayReportAsPdf() {
		String command = Config.getOpenReportCmd() + " " + Config.getTmpReportFile();
		try {
			Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			mainWindow.showError(e);
		}
	}

	protected void generateReport() {
		try {
			String report = reports[window.getSelectedReport()].toString();
			GenerateJasperReport generator = new GenerateJasperReport(connection, report);
			generator.generate(createParamsMap());
			generator.exportPDF(Config.getTmpReportFile());
			displayReportAsPdf();
//			Image reportImg = window.displayReport(generator.exportAsImage());
		} catch (Exception e) {
			mainWindow.showError(e);
		}
		window.hide();
	}

	private Map<String, Object> createParamsMap() {
		Map<String,Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put(CURRENT_YEAR, window.getSelectedYear());
		return paramsMap;
	}
}
